package com.example.androidkt.sixth

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.androidkt.fifth.ItemBean

@Database(version = 2, entities = [User::class,Book::class])
abstract class AppDataBase : RoomDatabase() {

    abstract fun userDao(): UserDao
    abstract fun bookDao():BookDao

    //数据库更新操作，定义操作的SQ语句，
    // 版本更新 version = ？？？？
    // 通知更新 addMigrations
    companion object {
        val MIGRATION_1_2 = object : Migration(1,2){
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("create table book(id integer primary key autoincrement not null,name text not null,pages integer not null)")
            }
        }

        val MIGRATION_2_3 = object : Migration(2,3){
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("alter table book add column author text not null default\"unknown\" ")
            }
        }

        val str = "He said, \"Hello, World!\""

        @Volatile private var instance: AppDataBase? = null

        @Synchronized
        fun getDatabase(context: Context): AppDataBase {
            instance?.let {
                return it
            }
            return Room.databaseBuilder(
                context.applicationContext,
                AppDataBase::class.java,
                "app_database"
            ).allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2)
                .addMigrations(MIGRATION_2_3)
//                .fallbackToDestructiveMigration() 暴力更新，使用最新的代码 addMigrations version一系列不用在修改，直接覆盖掉
                .build()
                .apply {
                instance = this
            }
            //.allowMainThreadQueries()允许在主线程，测试时可以用
        }

/*            instance ?: synchronized(this) {
                instance ?: Room.databaseBuilder(
                    context.applicationContext,
                    AppDataBase::class.java, "user.db"
                ).allowMainThreadQueries().build().also { instance = it }
            }*/


    }


//    返回破坏迁移会将当前的数据库销毁，然后在重新创建，随之而来的问题就是数据全部丢失，适合测试阶段。
//    Room.databaseBuilder(context.applicationContext，AppDatabase类的构造函数，
//    "app_database").fallbackToDestructiveMigrationO.build()
}